package com.sx.basic.pageable;

import com.sx.basic.BasicEntity;
import lombok.Data;
import org.springframework.data.domain.Sort;

import java.util.HashMap;
import java.util.Map;
import java.util.function.BiConsumer;

/**
 * @author AdinZ
 * @date 2020/11/10 15:33
 */
public class Condition extends BasicEntity {

    private Map<String,ConditionValue> map=new HashMap<>();
    private Sort sort=Sort.unsorted();

    public Condition eq(String column,Object value){
        return this.of(Keyword.EQ,column,value);
    }
    public Condition in(String column,Object... value){
        return of(Keyword.IN,column,value);
    }

    public Condition like(String column,Object value){
        return this.of(Keyword.LIKE,column,value);
    }
    public Condition ne(String column,Object value){
        return this.of(Keyword.NE,column,value);
    }
    public Condition gt(String column,Object value){
        return this.of(Keyword.GT,column,value);
    }
    public Condition ge(String column,Object value){
        return this.of(Keyword.GE,column,value);
    }
    public Condition lt(String column,Object value){
        return this.of(Keyword.LT,column,value);
    }
    public Condition le(String column,Object value){
        return this.of(Keyword.LE,column,value);
    }
    public Condition isNull(String column,Object value){
        return this.of(Keyword.IS_NULL,column,value);
    }

    public Condition isNotNull(String column,Object value){
        return this.of(Keyword.IS_NOT_NULL,column,value);
    }

    public Condition sort(Sort sort){
        this.sort=sort;
        return this;
    }
    public Condition sort(Sort.Direction direction, String... properties){
        this.sort=Sort.by(direction,properties);
        return this;
    }

    public Sort getSort() {
        return sort;
    }

    /**
     * 条件
     * @param type 条件类型
     * @param column 数据库键值
     * @param value
     * @return
     */
    public Condition of(Keyword type,String column,Object value){
        this.map.put(column,new ConditionValue(type,value));
        return this;
    }

    public boolean isEmpty() {
        return map.isEmpty();
    }
    public void forEach(BiConsumer<String,ConditionValue> action){
        this.map.forEach(action);
    }

    @Data
    public static class ConditionValue extends BasicEntity{
        private final Keyword keyword;
        private final Object value;
        public ConditionValue(Keyword keyword, Object value) {
            this.keyword = keyword;
            this.value = value;
        }
    }

    public enum Keyword{
        IN("IN"),
        LIKE("LIKE"),
        EQ("="),
        NE("<>"),
        GT(">"),
        GE(">="),
        LT("<"),
        LE("<="),
        IS_NULL("IS NULL"),
        IS_NOT_NULL("IS NOT NULL");

        Keyword(String name) {

        }
    }

}
